package com.north.light.androidutils.rxjava;

import java.util.concurrent.TimeUnit;

import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.core.ObservableSource;
import io.reactivex.rxjava3.functions.Function;

/**
 * FileName: RxBaseRetryFunction
 * Author: lzt
 * Date: 2022/8/10 14:18
 */
public class RxBaseRetryFunction implements Function<Observable<Throwable>, ObservableSource<?>> {
    private int maxConnectCount;
    private int currentRetryCount;
    private long waitRetryTime;

    public RxBaseRetryFunction(int var1, long var2) {
        this.maxConnectCount = var1;
        this.waitRetryTime = var2;
    }

    public ObservableSource<?> apply(Observable<Throwable> var1) {
        return var1.flatMap(new Function<Throwable, ObservableSource<?>>() {
            public ObservableSource<?> apply(Throwable var1) {
                if (var1 instanceof Exception) {
                    if (RxBaseRetryFunction.this.currentRetryCount < RxBaseRetryFunction.this.maxConnectCount) {
                        RxBaseRetryFunction.this.currentRetryCount++;
                        return Observable.just(1).delay(RxBaseRetryFunction.this.waitRetryTime, TimeUnit.MILLISECONDS);
                    } else {
                        return Observable.error(var1);
                    }
                } else {
                    return Observable.error(var1);
                }
            }
        });
    }
}
